package com.chen.forum.controller;

import com.chen.forum.DTO.CommentDTO;
import com.chen.forum.DTO.QuestionDTO;
import com.chen.forum.Service.CommentService;
import com.chen.forum.Service.QuestionService;
import com.chen.forum.enums.CommentTypeEnum;
import com.mysql.cj.protocol.x.ReusableInputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private CommentService commentService;


    @GetMapping("/question/{id}")
    public String question(
            @PathVariable(name="id") long id, Model model){
        QuestionDTO questionDTO=questionService.getById(id);
        List<QuestionDTO> relatedQuestions=questionService.selectRelated(questionDTO);
        List<CommentDTO> comments= commentService.listByQuestionId(id, CommentTypeEnum.QUESTION);
        questionService.incView(id);
        model.addAttribute("question",questionDTO);
        model.addAttribute("comments",comments);
        model.addAttribute("relatedQuestions",relatedQuestions);
        return "question";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable(name="id") long id){
        questionService.delete(id);
        return "redirect:/";
    }
    //重复点赞返回1   不重复返回0
    @PostMapping("/like/{id}")
    @ResponseBody
    public int like(@PathVariable(name="id")long questionid,
                     @RequestParam(name="userid") String userid){
        System.out.println(questionid);
        System.out.println(userid);
        if(userid.equals("0")){
            return 2;
        }
        int repeatlike = questionService.like(questionid, Integer.parseInt(userid));
        return repeatlike;
    }
}
